//
//  myloginPage.m
//  mintHome
//
//  Created by 朱彦名 on 16/6/15.
//  Copyright © 2016年 朱彦名. All rights reserved.
//

#import "myloginPage.h"
#import "tabelViewOfLogin.h"
#import "tabelViewOfLoginCell.h"
#import "loginViewController.h"
#import "ClearCache.h"
#import "collectViewController.h"
#import "aboutUsViewController.h"
@interface myloginPage ()<UITableViewDelegate,UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, retain)tabelViewOfLogin * tableview1;
@property (nonatomic, retain)UIImageView *image1;
@property (nonatomic, retain)UIImageView *headImg;
@property (nonatomic ,retain) UIButton *loginOfUser;
@property (nonatomic, retain) UISwitch *swich;
@property (nonatomic, retain) UISwitch *swichOfNight;
@property (nonatomic, retain) NSString *imgPath;


@end

@implementation myloginPage

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatTableView];
    self.tableview1.tableHeaderView = [self creatHeaderView];
    
    self.navigationItem.title = @"user";
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)creatTableView{

    self.tableview1 = [[tabelViewOfLogin alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    
    [self.view addSubview:self.tableview1];
    self.tableview1.delegate = self;
    self.tableview1.dataSource = self;
    
    [self.tableview1 registerClass:[tabelViewOfLoginCell class] forCellReuseIdentifier:@"pool"];
    
    

}
#pragma mark - 建立视图
- (UIImageView *)creatHeaderView{

    UIImageView *header = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 3)];
    header.image = [UIImage imageNamed:@"moreSortBack.JPG"];
    header.userInteractionEnabled = YES;
    
    
    
    self.headImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, header.frame.size.width / 4, header.frame.size.width / 4)];
    _headImg.backgroundColor = [UIColor purpleColor];
    [header addSubview:_headImg];
    _headImg.center = header.center;
    _headImg.layer.cornerRadius =  header.frame.size.width / 8;
    _headImg.clipsToBounds = YES;
    //开启图片用户交互
    _headImg.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.headImg addGestureRecognizer:tap];
    
    NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
    if ([userdefault dataForKey:@"img"]) {
        [_headImg setImage:[UIImage imageWithData:[userdefault dataForKey:@"img"]]];
        
        
    }
    
    
    

//    self.loginOfUser = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.loginOfUser.frame = CGRectMake(0, 0, 80, 30);
//    self.loginOfUser.center = CGPointMake(header.center.x, header.center.y + header.frame.size.height / 4 + 15);
//    [header addSubview:self.loginOfUser];
//    
//    [self.loginOfUser setTitle:@"登录" forState:UIControlStateNormal];
//    [self.loginOfUser setTitle:@"退出" forState:UIControlStateSelected];
//    
//    [self.loginOfUser setTintColor:[UIColor redColor]];
//    
//    
//    [self.loginOfUser addTarget:self action:@selector(handleLogin:) forControlEvents:UIControlEventTouchDown];
//    BOOL login = [[NSUserDefaults standardUserDefaults] boolForKey:@"didlogin"];
//    
//    _loginOfUser.selected = login;
    

    
    return header;

}
#pragma mark - 点击头像实现
- (void)tapAction: (UITapGestureRecognizer *)tap{

    NSLog(@"xiangce");
    //创建弹出视图
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    /** 打开相机 */
    UIAlertAction *call = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //判断是否可以打开相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;  //是否可编辑
            //摄像头
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];
            [picker release];
        }else{
            
            /** 提示 */
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"Error" message:@"您的设备没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alertVc addAction:cancel];
            [self presentViewController:alertVc animated:YES completion:nil];
        }
    }];
    
    /** 打开系统相册 */
    UIAlertAction *message = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        //签代理
        picker.delegate = self;
        //允许可点击照片并编辑
        picker.allowsEditing = YES;
        
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //转场动画
        picker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        //模态推出
        [self presentViewController:picker animated:YES completion:^{
            
        }];
        
        [picker release];
        
        
    }];
    
    /** 取消 */
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertVc addAction:call];
    [alertVc addAction:message];
    [alertVc addAction:cancel];
    [self presentViewController:alertVc animated:YES completion:nil];

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //保存编辑后的照片
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    
    /**< 如果不为空时,就设为选择后图片 */
    if (img != nil) {
        _headImg.image = img;
    }
    
    
    //要保存到沙盒里 下一次打开还会显示  图片转成data类型来保存
    NSData *data;
    //要判断图片是什么类型 就两种
    if (UIImagePNGRepresentation(img)) {
        
        data = UIImagePNGRepresentation(img);
    }else{
        
        data = UIImageJPEGRepresentation(img, 1.0);
    }
    
    /** 存沙盒 */
    [[NSFileManager defaultManager]createFileAtPath:_imgPath contents:data attributes:nil];
    
    //保存
    NSUserDefaults *usetFaults = [NSUserDefaults standardUserDefaults];
    [usetFaults setObject:data forKey:@"img"];
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


#pragma mark - 登录
//- (void)handleLogin: (UIButton *)button{
//    
//    BOOL login = [[NSUserDefaults standardUserDefaults]boolForKey:@"didlogin"];
//    loginViewController *login1 = [[loginViewController alloc]init];
//    if (login) {
//        _loginOfUser.selected = YES;
//        
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否退出" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            
//        }];
//        
//        UIAlertAction *logout = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            
//            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//            [user removeObjectForKey:@"didlogin"];
//            
//            _loginOfUser.selected = !_loginOfUser.selected;
//            
//        }];
//        [alert addAction:cancel];
//        [alert addAction:logout];
//        [self presentViewController:alert animated:YES completion:^{
//            
//        }];
//        
//        
//        
//    }else{
//    
//    [self.navigationController pushViewController:login1 animated:YES];
//    }
//    
//}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 4;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 2;
    }else {
        return 3;
    }
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    tabelViewOfLoginCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool" forIndexPath:indexPath];
    NSArray *arr = @[@"清理缓存", @"夜间模式", @"收藏", @"关于薄荷家居", @"联系我们"];
    NSArray *arrOfImage = @[@"wipecache@2x.png", @"night@2x.png",@"collect@2x", @"set@2x", @"contact@2x"];
    
    BOOL model = [AccountManager sharedInstance].isNight;
    if (model == YES) {
        cell.backgroundColor = [UIColor silverColor];
        
    }else{
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    if (indexPath.section == 0) {
        
        self.swich = [[UISwitch alloc]initWithFrame:CGRectZero];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.accessoryView = _swich;
        cell.labelOfTable.text = @"本地推送";
        
        [self.swich addTarget:self action:@selector(handelSend1:time:) forControlEvents:UIControlEventValueChanged];
        
    }else if (indexPath.section == 1){
        
        if (indexPath.row == 1 ) {
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            self.swichOfNight = [[UISwitch alloc]initWithFrame:CGRectZero];
            
            cell.accessoryView = _swichOfNight;
            
            if ([AccountManager sharedInstance].isNight) {
                _swichOfNight.on = YES;
            }else{
                _swichOfNight.on = NO;
                
            }
            
            [self.swichOfNight addTarget:self action:@selector(setNightModel:) forControlEvents:UIControlEventValueChanged];
            
        }
        
        cell.labelOfTable.text = arr[indexPath.row];
        cell.imageView.image = [UIImage imageNamed:arrOfImage[indexPath.row]];
        
    }else if (indexPath.section == 2){
        cell.labelOfTable.text = arr[indexPath.row + 2];
        if (indexPath.row != 2) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.imageView.image = [UIImage imageNamed:arrOfImage[indexPath.row + 2]];
        
    }
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 10)];
    view1.backgroundColor = [UIColor lightGrayColor];
    return view1;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    

    //清理缓存
     if (indexPath.section == 1 && indexPath.row == 0){
        NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        CGFloat cache = [ClearCache folderOfSize:path];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"缓存清理" message:[NSString stringWithFormat:@"正在清理%.2lfMB缓存", cache] preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        [self performSelector:@selector(dismissAlert) withObject:alert afterDelay:1.5];
    }
    //夜间模式
    else if (indexPath.section == 1 && indexPath.row == 1){
        
    
    }
    //收藏
    else if (indexPath.section == 2 && indexPath.row == 0){
        collectViewController *col = [[collectViewController alloc]init];
        [self.navigationController pushViewController:col animated:YES];
        
    
    }
    //关于我们
    else if (indexPath.section == 2 && indexPath.row == 1){
        
        aboutUsViewController *about = [[aboutUsViewController alloc]init];
        
        [self.navigationController pushViewController:about animated:YES];
    
    }
    //联系我们
    else if (indexPath.section == 2 && indexPath.row == 2){
    
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *call = [UIAlertAction actionWithTitle:@"打电话给好友" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:@"tel://10086"];
            [[UIApplication sharedApplication] openURL:url];
            
        }];
        
        UIAlertAction *message = [UIAlertAction actionWithTitle:@"发短信给好友" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:@"sms://10086"];
            [[UIApplication sharedApplication] openURL:url];
            
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertVc addAction:call];
        [alertVc addAction:message];
        [alertVc addAction:cancel];
        [self presentViewController:alertVc animated:YES completion:nil];
        
        
    
    }

}
#pragma mark - 清理缓存
- (void)dismissAlert{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    [ClearCache clearCache:path];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    [self.tableview1 reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
    [self dismissViewControllerAnimated:YES completion:^{
    
    }];
    

}
#pragma mark - 夜间模式
- (void)setNightModel: (UISwitch *)swich{

        if (![AccountManager sharedInstance].isNight) {
            self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
            self.tabBarController.tabBar.barStyle = UIBarStyleBlack;
            _tableview1.backgroundColor = [UIColor silverColor];
        } else {
            self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
            self.tabBarController.tabBar.barStyle = UIBarStyleDefault;
            _tableview1.backgroundColor = [UIColor whiteColor];
        }
        [AccountManager sharedInstance].isNight = ![AccountManager sharedInstance].isNight;
}

- (void)setLightDay{
    [NightManager setBackgroundColorWithView:self.view];
    [_tableview1 reloadData];

}
- (void)setNightDay{
    [NightManager setBackgroundColorWithView:self.view];
    [_tableview1 reloadData];
    
}
//本地推送通知
- (void)handelSend1: (UISwitch *)swich time:(NSInteger)alertTime{
    

    if ([swich isOn]) {
        
        UILocalNotification *notification = [[UILocalNotification alloc]init];
        
        NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
        
        notification.fireDate = fireDate;
        
        notification.timeZone = [NSTimeZone defaultTimeZone];
        
//        notification.repeatInterval = kCFCalendarUnitMinute;
        
        notification.alertBody = @"来消息了";
        notification.applicationIconBadgeNumber = 1;
        
        //通知参数
        NSDictionary *userDic = [NSDictionary dictionaryWithObject:@"本地推送" forKey:@"key" ];
        
        notification.userInfo = userDic;
        
        if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            // 通知重复提示的单位，可以是天、周、月
            notification.repeatInterval = NSCalendarUnitDay;
        } else {
            // 通知重复提示的单位，可以是天、周、月
            notification.repeatInterval = NSCalendarUnitDay;
        }
        
        // 执行通知注册
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
}



- (void)viewWillAppear:(BOOL)animated{
    
    [self.tableview1 reloadData];
    
}

@end
